import 'package:flutter/material.dart';

class LYGradientText extends StatefulWidget {
  @override
  State<LYGradientText> createState() => _LYGradientTextState();
}

class _LYGradientTextState extends State<LYGradientText> {
  Paint? foreground;
  @override
  void initState() {

    // TODO: implement initState
    super.initState();
    final size = boundingTextSize("World!asdasdasdasd", TextStyle());
    debugPrint('==${size}');
    foreground = Paint()
      ..shader = const LinearGradient(colors: [Colors.red, Colors.blue])
          .createShader(Rect.fromLTWH(0, 0.0, size.width * 3, size.height * 3),
              textDirection: TextDirection.ltr);
  }

  @override
  Widget build(BuildContext context) {
    final title = "提灯走一123😂";
    final size = boundingTextSize(
        title, TextStyle(fontSize: 24, fontWeight: FontWeight.bold));
    final scale = MediaQueryData.fromView(View.of(context)).devicePixelRatio;
    return Container(
      decoration: BoxDecoration(border: Border.all(color: Colors.red)),
      child: Text(title,
          style: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
            foreground: Paint()
              ..shader = const LinearGradient(colors: [
                Color(0xFF4F81E7),
                Color(0xFFF70FFF),
                // Colors.red,
                // Colors.blue
              ]).createShader(Rect.fromLTWH(0, 0.0, size.width, size.height),
                  textDirection: TextDirection.ltr),
          )),
    );
  }

  static Size boundingTextSize(String? text, TextStyle style,
      {int maxLines = 2 ^ 31, double maxWidth = double.infinity}) {
    if (text == null || text.isEmpty) {
      return Size.zero;
    }
    final TextPainter textPainter = TextPainter(
        textDirection: TextDirection.ltr,
        text: TextSpan(text: text, style: style),
        maxLines: maxLines)
      ..layout(maxWidth: maxWidth);
    return textPainter.size;
  }
}
